/* 
 *  Document   : RIA
 *  Created on : 2011-6-16, 20:49:49
 *  Author     : GodSon
 *  Email      : wmails@126.com
 *  Link       : http://www.btboys.com
 *  Vsersion   : 0.1 
 */

/**
 * 公共核心包 RIA  </br>
 * RIA.<b>Class</b>      创建类调用 RIA.Class({initialize:function(){}});</br>
 * RIA.<b>nameSpace</b>  创建命名空间。param：name</br>
 * RIA.<b>loadJs</b>     加载javascript。param：url</br>
 * RIA.<b>loadCSS</b>    加载样式。param：url</br>
 * RIA.<b>importMD</b>   导入模块。param：name模块名</br>
 * RIA.<b>logout</b>     调试信息输出。param：mgs需输出的内容</br>
 * RIA.<b>window</b>     创建弹出窗口。param：option</br>
 * RIA.<b>getNs</b>      获取命名空间。param：name</br>
 * RIA.<b>util</b>       工具包。RIA.util.&LT;isIE | getUUID | random | json2str ></br>
 * RIA.<b>config</b>     全局配置</br>
 * RIA.<b>module</b>     模块</br>
 */
var RIA = (function(){
    return {
        Class: function(obj, supr) { 
            var sb = obj.initialize, sp;  
            delete obj.initialize;  
            if (!supr || typeof supr === 'object') {  
                sb.prototype = obj;  
            } else {  
                sp = function() {};  
                sp.prototype = supr.prototype;  
                sb.prototype = new sp();  
                sb.supr = sp.prototype;  
                jQuery.extend(sb.prototype, obj);  
            }  
            sb.prototype.constructor = sb;  
            return sb;  
        }, 
        nameSpace:function(ns,cb){      
            ns = RIA.config.baseNs+"."+ns;
            var nsArr = ns.split('.'), o;  
            o = window[nsArr[0]] = window[nsArr[0]] || {};  
            jQuery.each(nsArr.slice(1), function(i, n) {  
                o = o[n] = o[n] || {};  
            });  
            RIA.module[nsArr.slice(-1)].ns = eval(ns);  
            if (cb && typeof cb === 'function') cb.call(o);  
        },
        loadJs:function(url,callback){
            var done = false;
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.language = 'javascript';
            script.charset = 'UTF-8';
            script.src = url;
            script.onload = script.onreadystatechange = function(){
                if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')){
                    done = true;
                    script.onload = script.onreadystatechange = null;
                    if (callback){
                        callback.call();
                    }
                    $(script).remove();
                }
            }
            document.getElementsByTagName("head")[0].appendChild(script);
        },
        loadCSS:function(url){
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.media = 'screen';
            link.href = url;
            document.getElementsByTagName('head')[0].appendChild(link);
        },
        importMD: function(name, callback) {
            if (RIA.module[name].ns) {  
                callback.call(RIA.module[name].ns);  
                return;
            }
            var mm = [];
            if (typeof name == 'string'){
                add(name);
            } else {
                for(var i=0; i<name.length; i++){
                    add(name[i]);
                }
            }
            function add(name){
                if (!RIA.module[name]) return;
                var d = RIA.module[name]['dependencies'];
                if (d){
                    for(var i=0; i<d.length; i++){
                        add(d[i]);
                    }
                }
                mm.push(name);
            }
                
            function loadMm(){
                if (mm.length){
                    var m = mm[0]; 
                    if (!RIA.module[m].ns){
                        loadSingle(m, function(){
                            mm.shift();
                            loadMm();
                        });
                    } else{
                        mm.shift();
                        loadMm();
                    }
                } else {
                    if (callback){
                        callback.call(RIA.module[name].ns);
                    }
                }
            }
            loadMm();
            
            function loadSingle(name, callback){
                var module = RIA.module[name];
                if (module['css']){
                    var url = module['css'];
                    RIA.loadCSS(url);
                }
                RIA.loadJs(module['js'], function(){
                    if (callback){
                        callback.call();
                    }
                });
            }
        },
        logout:function(msg){
            if (window.console && window.console.log) {
                window.console.log(msg);
            }else if (window.opera && window.opera.postError) {
                window.opera.postError(msg);
            }else{
                throw new Error(msg);
            }
        },
        window:function(option){
            jQuery.createWin(option);
        },
        grid:function(config){
            //默认配置
            var defaultConfig = {
                loadMsg: "加载中,请稍后……",
                fit: true,
                nowrap: true,
                striped: false,
                remoteSort: true,
                fitColumns: true,
                pagination: true,
                pageList:[15,30,50],
                remoteSort:false,
                striped:true,
                rownumbers:true,
                rowStyler: function(){
                    return "line-height: 22px;cursor: pointer;";
                }
            };
            config = $.extend({}, defaultConfig, config || {});
            //初始化datagrid
            $('#'+config.id).datagrid(config);
        },
        getNs:function(ns){
            return  eval("RIA.module."+ns+".ns");
        },
        util: { // 工具集    
            isIE: function() {  
                return jQuery.browser.msie;  
            },
            getUUID:function() {  
                return "UUID-"+(RIA.util.random()+RIA.util.random()+"-"+RIA.util.random()+"-"+
                    RIA.util.random()+"-"+RIA.util.random()+"-"+RIA.util.random()+RIA.util.random()+RIA.util.random());  
            },
            random:function(){
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            },
            json2str:function(json){
                var arr = [];
                var fmt = function(s) {
                    if (typeof s == 'object' && s != null) return json2str(s);
                    return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
                }
                for (var i in json) arr.push("'" + i + "':" + fmt(json[i]));
                return '{' + arr.join(',') + '}';
            },
            cookie:{
                set:function(name,value){
                    var exp  = new Date();    //new Date("December 31, 9998");
                    exp.setTime(exp.getTime() + 900*1000);//保存15分钟
                    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
                },
                get:function(name){
                    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
                    if(arr != null) return unescape(arr[2]);
                    return null;
                },
                del:function(name){
                    var exp = new Date();
                    exp.setTime(exp.getTime() - 1);
                    var cval=RIA.util.cookie.get(name);
                    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
                }
            }
        },
        config:{ //全局配置
            baseNs:"Godson.os"
        },
        module: {} // 注册模块及其路径
    }
})();